package com.itheima.service.cargo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.UtilFuns;
import com.itheima.dao.cargo.ContractDao;
import com.itheima.dao.cargo.ContractProductDao;
import com.itheima.dao.cargo.ExtCproductDao;
import com.itheima.doamin.cargo.*;
import com.itheima.service.cargo.ContractService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class ContractServiceImpl implements ContractService {
    @Autowired
    ContractDao contractDao;
    @Autowired
    ExtCproductDao extCproductDao;
    @Autowired
    ContractProductDao contractProductDao;

    @Override
    public Contract findById(String id) {
        return contractDao.selectByPrimaryKey(id);
    }

    @Override
    public void save(Contract contract) {
        contract.setId(UtilFuns.getUUID());
        contract.setState(0);
        contract.setTotalAmount(0d);
        contract.setProNum(0);;
        contract.setExtNum(0);
        contract.setCreateTime(new Date());
        contractDao.insertSelective(contract);
    }

    @Override
    public void update(Contract contract) {
        //更新
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public void delete(String id) {
        //根据合同的id取出合同下的所有附件
        //创建附件查询条件
        ExtCproductExample extCproductExample=new ExtCproductExample();
        extCproductExample.createCriteria().andContractIdEqualTo(id);
        List<ExtCproduct> extCproducts = extCproductDao.selectByExample(extCproductExample);
        //遍历删除
        for (int i=0;i<extCproducts.size();i++){
            extCproductDao.deleteByPrimaryKey(extCproducts.get(i).getId());
        }

        //删除合同下的货物
        //创建查询条件
        ContractProductExample contractProductExample=new ContractProductExample();
        contractProductExample.createCriteria().andContractIdEqualTo(id);
        List<ContractProduct> contractProducts = contractProductDao.selectByExample(contractProductExample);
        for (int j=0;j<contractProducts.size();j++){
            contractProductDao.deleteByPrimaryKey(contractProducts.get(j).getId());
        }

        //对合同进行删除
        contractDao.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo findAll(ContractExample example, int page, int size) {
        PageHelper.startPage(page,size);
        List<Contract> contracts = contractDao.selectByExample(example);
        return new PageInfo(contracts);
    }

    @Override
    public List<ContractProductVo> selectAllContractVo(String inputDate, String companyId) {
        return contractDao.selectAllContractVo(inputDate,companyId);
    }
}
